package org.clipjoint.controller;

import com.alibaba.fastjson.JSON;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang3.StringUtils;
import org.clipjoint.vo.JsonResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * 文件上传下载相关请求
 *
 * @author 陈光耀
 * date: 2021-1-11
 */
@WebServlet("/file")
public class FileController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String method = request.getParameter("method");

        switch (method) {
            case "layuiUpload":
                layuiUpload(request, response);
                break;
//            case "ossTempUrl":
//                ossTempUrl(request, response);
//                break;
        }

    }

    // 重定向到oss临时地址
//    private void ossTempUrl(HttpServletRequest request, HttpServletResponse response) throws IOException {
//
//        // 获取对象名称
//        String objectName = request.getParameter("objectName");
//
//        // 获取临时url地址
//        URL tempUrl = AliyunOSSUtil.getTempUrl(objectName);
//
//        // 重定向
//        response.sendRedirect(tempUrl.toString());
//
//    }

    // layui上传插件上传接口
    private void layuiUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {

        // 1.创建磁盘文件项工厂对象
        DiskFileItemFactory factory = new DiskFileItemFactory();

        // 2.创建一个servlet文件上传处理对象
        ServletFileUpload servletFileUpload = new ServletFileUpload(factory);

        // 3.解析request对象
        List<FileItem> fileItems = new ArrayList<>();
        try {
            fileItems = servletFileUpload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

        // 4.遍历判断是否是普通表单字段
        JsonResult result = null;
        for (FileItem fileItem : fileItems) {
            if (!fileItem.isFormField()) {
                // 获取文件名
                String fileName = fileItem.getName();
                if (StringUtils.isBlank(fileName)) {
                    continue;
                }
                String realPath = request.getServletContext().getRealPath("upload");
                // 生成随机文件名用于保存
                String saveName = UUID.randomUUID().toString() + "-" + fileName;

                try {
                    // 将文件上传到阿里云OSS
//                    AliyunOSSUtil.upload(fileItem.getInputStream(), saveName);
                    //将文件写到本地
                    fileItem.write(new File(realPath + File.separator + saveName));
                    // 将图片地址存入响应vo
                    Map<String, String> map = new HashMap<>();
                    map.put("src", "upload/" + saveName);
                    result = JsonResult.builder().code(0).msg("上传成功").data(map).build();
                } catch (Exception e) {
                    e.printStackTrace();
                    result = JsonResult.builder().code(1).msg("上传失败").build();
                }

            }
        }

        // 5.将结果格式化json字符串写回
        response.getWriter().print(JSON.toJSONString(result));

    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}
